package com.qianclass.talklive.app.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.qianclass.talklive.R;
import com.qianclass.talklive.app.activity.ExpressionUtil;
import com.qianclass.talklive.app.bean.TranslationBean;
import com.qianclass.talklive.app.bean.VideoBody;
import com.qianclass.talklive.app.utils.DensityUtil;
import com.qianclass.talklive.app.utils.LogUtil;
import com.qianclass.talklive.app.utils.ToastUtils;
import com.qianclass.talklive.app.view.MyListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class ChatHistoryAdapter extends BaseAdapter implements View.OnLongClickListener {

	private static final int SUCCESS = 0;
	public Drawable drawable;
	public String text;
	private Context context;
	private List<VideoBody> mVideoBody;
	private LayoutInflater inflater;
	private String userName;
	private PopupWindow mPopupWindow;
	private View mView;
	private String mTranslationWords;
	private String TRANSLATION;

	public ChatHistoryAdapter(Context context, List<VideoBody> mVideoBody) {
		this.context = context;
		inflater = LayoutInflater.from(context);
		this.mVideoBody = mVideoBody;
	}

	public void updateData(List<VideoBody> videoBody){
		mVideoBody = videoBody;
		notifyDataSetChanged();
	}

	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case SUCCESS:
					String jsonstr = (String) msg.obj;
					processJsonData(jsonstr);
					break;
				default:
					break;
			}
		}
	};
	
	@Override
	public int getCount() {
		return mVideoBody != null ? mVideoBody.size() : 0;
	}

	@Override
	public Object getItem(int position) {
		return mVideoBody != null ? mVideoBody.get(position) : null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public boolean isEnabled(int position) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder viewHolder = null;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.chathistory_item, null);

			viewHolder = new ViewHolder();
			viewHolder.tv_sendtime = (TextView) convertView.findViewById(R.id.tv_sendtime);
			viewHolder.tv_chatcontent = (TextView) convertView.findViewById(R.id.tv_chatcontent);

			viewHolder.tv_username = (TextView) convertView.findViewById(R.id.tv_username);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}

		text = mVideoBody.get(position).getText();
		String zhengze = "</0[0-9]{2}/>";
		SpannableString spannableString = ExpressionUtil.getExpressionString(this.context, text, zhengze);

		int usertype = mVideoBody.get(position).getUsertype();

		switch (usertype) {
			case 1:
				break;

			case 2:
				break;

			case 3:
				break;

			case 4:
				break;

			default:
				break;
		}

		if (mVideoBody.get(position).getUsertype() == 4) {
			viewHolder.tv_chatcontent.setTextColor(Color.parseColor("#FF4081"));
			viewHolder.tv_sendtime.setTextColor(Color.parseColor("#FF4081"));
			viewHolder.tv_username.setTextColor(Color.parseColor("#FF4081"));
		} else {
			viewHolder.tv_chatcontent.setTextColor(Color.parseColor("#000000"));
			viewHolder.tv_sendtime.setTextColor(Color.parseColor("#4cc5fc"));
			viewHolder.tv_username.setTextColor(Color.parseColor("#4cc5fc"));
		}
		viewHolder.tv_chatcontent.setText(spannableString);
		viewHolder.tv_sendtime.setText(mVideoBody.get(position).getTime());
		viewHolder.tv_username.setText(mVideoBody.get(position).getUser());

		viewHolder.tv_chatcontent.setOnLongClickListener(this);
		mView = parent.getRootView();

		return convertView;
	}

	@Override
	public boolean onLongClick(View v) {
		switch (v.getId()) {
			case R.id.tv_chatcontent:

				TextView textView = (TextView) v;
				mTranslationWords = textView.getText().toString().trim();

				final String[] strs = {/*"复制", */"翻译"};
				TRANSLATION = strs[0];
				if (mPopupWindow == null) {
					int width = DensityUtil.dip2px(context, 50);

					mPopupWindow = new PopupWindow(width, WindowManager.LayoutParams.WRAP_CONTENT);

					ListView contentView = new ListView(context);
					contentView.setDividerHeight(0);
					contentView.setBackgroundColor(context.getResources().getColor(R.color.app_background));
					contentView.setAdapter(new ChatAdapter(strs));

					//使用ListView来填充PopupWindow
					mPopupWindow.setContentView(contentView);
					//设置PopupWindow区域外部触摸关闭
					mPopupWindow.setOutsideTouchable(true);
					mPopupWindow.setBackgroundDrawable(new ColorDrawable());
				}
				//mPopupWindow.showAsDropDown(mView, DensityUtil.dip2px(context,50), 0);
				WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);

				int screenWidth = windowManager.getDefaultDisplay().getWidth();

				mPopupWindow.showAtLocation(mView, Gravity.CENTER | Gravity.RIGHT, screenWidth / 8, 0);

				break;
			default:
				break;
		}
		return true;
	}

	private void translate(final String words) {
		//http://fanyi.youdao.com/openapi.do
		// ?keyfrom=eClass&key=1338232813&type=data&doctype=json&version=1.1&q=good
		new Thread(new Runnable() {
			@Override
			public void run() {
			try {
				OkHttpClient okHttpClient = new OkHttpClient();
				String url = "http://fanyi.youdao.com/openapi.do";
				Map<String, Object> paramsMap = new HashMap<>();
				paramsMap.put("keyfrom", "eClass");
				paramsMap.put("key", "1338232813");
				paramsMap.put("type", "data");
				paramsMap.put("doctype", "json");
				paramsMap.put("version", "1.1");
				paramsMap.put("q", words);
				String urlParamsByMap = getUrlParamsByMap(paramsMap);

				url = url + "?" +  urlParamsByMap;

				Request request = new Request.Builder().get()
													   .url(url)
													   .build();

				Response response = okHttpClient.newCall(request)
										   .execute();
				if(response.isSuccessful()){
					String jsonStr = response.body()
											 .string();
					LogUtil.e("--json--", jsonStr);
					//processJsonData(jsonStr);
					Message msg = Message.obtain();
					msg.obj = jsonStr;
					msg.what = SUCCESS;
					mHandler.sendMessage(msg);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

			}
		}).start();

	}

	/**
	 * 这是Url地址中参数拼接的方法
	 * @param map
	 * @return
	 */
	public String getUrlParamsByMap(Map<String, Object> map) {
		if (map == null) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			sb.append(entry.getKey() + "=" + entry.getValue());
			sb.append("&");
		}
		String s = sb.toString();
		if (s.endsWith("&")) {
			s = s.substring(0, s.length() - 1);
		}
		return s;
	}

	private void processJsonData(String jsonStr) {
		String ukPhonetic = "";
		String usPhonetic = "";

		try {
			JSONObject jsonObject = new JSONObject(jsonStr);
			JSONObject basic      = jsonObject.getJSONObject("basic");
			ukPhonetic     = basic.getString("uk-phonetic");
			usPhonetic     = basic.getString("us-phonetic");
		} catch (JSONException e) {
			e.printStackTrace();
		}

		TranslationBean translationBean = JSON.parseObject(jsonStr, TranslationBean.class);

		AlertDialog.Builder builder         = new AlertDialog.Builder(context);
		View                view            = View.inflate(context, R.layout.dialog_translation, null);
		TextView            tvQuery         = (TextView) view.findViewById(R.id.tv_query);
		TextView            tvTranslation   = (TextView) view.findViewById(R.id.tv_translation);
		LinearLayout 		llUKPhonetic 		= (LinearLayout) view.findViewById(R.id.ll_uk_phonetic);
		LinearLayout 		llUSPhonetic 		= (LinearLayout) view.findViewById(R.id.ll_us_phonetic);
		TextView            tvUkPhonetic    = (TextView) view.findViewById(R.id.tv_uk_phonetic);
		TextView            tvUsPhonetic    = (TextView) view.findViewById(R.id.tv_us_phonetic);
		MyListView          lvParaphrase    = (MyListView) view.findViewById(R.id.lv_paraphrase);
		LinearLayout 		llWebParaphrase	= (LinearLayout) view.findViewById(R.id.ll_web_paraphrase);
		MyListView          lvNetParaphrase = (MyListView) view.findViewById(R.id.lv_net_paraphrase);
		TextView            tvNoTranslation    = (TextView) view.findViewById(R.id.tv_no_translation);

		tvQuery.setText(translationBean.getQuery());
		List<String> tsList = translationBean.getTranslation();
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < tsList.size(); i++) {
			if (i == tsList.size() - 1) {
				buffer.append(tsList.get(i));
			}else{
				buffer.append(tsList.get(i) + ",");
			}
		}
		tvTranslation.setText(buffer.toString());

		if (TextUtils.isEmpty(ukPhonetic) && TextUtils.isEmpty(usPhonetic)) {
			llUKPhonetic.setVisibility(View.GONE);
			llUSPhonetic.setVisibility(View.GONE);
		}

		tvUkPhonetic.setText("[" + ukPhonetic + "]");
		tvUsPhonetic.setText("[" + usPhonetic + "]");

		if (translationBean.getWeb() == null || translationBean.getWeb().size() == 0) {
			llWebParaphrase.setVisibility(View.GONE);
		}

		if(translationBean != null && translationBean.getBasic() != null){
			lvParaphrase.setAdapter(new NetParaphraseAdapter(context, translationBean, "basic"));
			lvNetParaphrase.setAdapter(new NetParaphraseAdapter(context, translationBean, "web"));
		}else{
			tvNoTranslation.setVisibility(View.VISIBLE);
		}

		builder.setView(view);
		AlertDialog dialog = builder.create();
		dialog.show();
		WindowManager.LayoutParams params = dialog.getWindow()
													  .getAttributes();
		params.width = DensityUtil.dip2px(context, 320);
		//params.height = DensityUtil.dip2px(context, 280);
		dialog.getWindow().setAttributes(params);

		dialog.setCancelable(true);
		dialog.setCanceledOnTouchOutside(true);
	}

	public static boolean isEnglishWords(String str) {
		String regex = ",|[.]|;|，|？|。|[?]|[\"]|[“”]|!|\\s+";
		String strAry[] = str.split(regex);
		for (int i = 0; i < strAry.length; i++) {
			for(int j=0; j< strAry[i].length(); j++){
				char ss = strAry[i].charAt(j);
				boolean s = String.valueOf(ss).matches("[^\\u4e00-\\u9fa5]");
				if(s){
					Pattern pattern = Pattern.compile("[a-zA-Z]*");
					Matcher isEnglish = pattern.matcher(strAry[i]);
					if (!isEnglish.matches()) {
						return false;
					}
				}else{
					return false;
				}
			}
		}
		return true;
	}

	public class ChatAdapter extends BaseAdapter{

		String[] strs;

		public ChatAdapter(String[] strs) {
			this.strs = strs;
		}

		@Override
		public int getCount() {
			return strs != null ? strs.length : 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			TextView textView = new TextView(context);
			textView.setTextSize(13);
			textView.setTextColor(Color.GRAY);
			textView.setPadding(DensityUtil.dip2px(context,3), 0, 0, 0);
			textView.setGravity(Gravity.CENTER_VERTICAL);
			textView.setHeight(DensityUtil.dip2px(context,30));
			textView.setText(strs[position]);
			textView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if(strs[position].equals(TRANSLATION)){
						//alertDialog.dismiss();
						mPopupWindow.dismiss();
						if (isEnglishWords(mTranslationWords)) {
							//翻译英文成中文
							translate(mTranslationWords);
						} else {
							ToastUtils.showToast(context, "暂时只开通英文翻译成中文");
						}
					}
				}
			});
			return textView;
		}
	}

	class ViewHolder {
		public TextView tv_username;
		public TextView tv_chatcontent;
		public TextView tv_sendtime;
	}
}


